﻿using System;
using System.Text.RegularExpressions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using VH.SharePoint.Api.Helpers;

namespace VH.SharePoint.Api
{
    public class PostItemCollection : ObjectCollection<PostItem>
    {
        internal PostItemCollection(BlogWeb blog, Guid targetList) : base(blog, targetList)
        {
            this.Query = DefautQuery();
        }

        public PostItem Add(PostItemInfo postInfo)
        {
            var layout = Blog.GetDefaultLayout();
            return layout==null || PublishingWeb.GetPagesListId(Blog.Web) != Blog.PostLibraryId ? AddSitePage(postInfo) : AddPublishingPage(postInfo, layout);
        }

        private PostItem AddSitePage(PostItemInfo postInfo)
        {
            using (new SPUnsafeUpdate(Blog.Web))
            {
                var folder = List.RootFolder;
                var fileName = GenerateFileName(postInfo.Title);
                var fileUrl = String.Format("{0}/{1}", folder.ServerRelativeUrl, fileName);
                var wikiPage = Blog.Web.GetFile(fileUrl);
                wikiPage = wikiPage.Exists?wikiPage:folder.Files.Add(String.Format("{0}/{1}", folder.ServerRelativeUrl, fileName), SPTemplateFileType.WikiPage);
                var post = (PostItem)wikiPage.Item;
                if (!string.IsNullOrEmpty(postInfo.Content))
                    post.Content = postInfo.Content;
                post.Item.SystemUpdate();
                return post;
            }
        }

        private PostItem AddPublishingPage(PostItemInfo postInfo, PageLayout layout)
        {
            using (new SPUnsafeUpdate(Blog.Web))
            {
                var w = PublishingWeb.GetPublishingWeb(Blog.Web);
                var fileName = GenerateFileName(postInfo.Title);
                var folder = List.RootFolder;
                var page = w.GetPublishingPage(folder.ServerRelativeUrl + "/" + fileName) ??
                           w.AddPublishingPage(fileName, layout, folder);
                var post = (PostItem) page;
                post.Title = postInfo.Title;
                if (!string.IsNullOrEmpty(postInfo.Content))
                    post.Content = postInfo.Content;
                post.Item.SystemUpdate();
                return post;
            }
        }
        
        private string GenerateFileName(string title)
        {
            string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
            string invalidReStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);
            var name =
                Regex.Replace(title, invalidReStr, "")
                     .Replace(" ", "-")
                     .Replace("--", "-")
                     .Replace("--", "-")
                     .Replace("--", "-");
            if (name.Length > 100)
            {
                name = name.Substring(0, 100);
            }
            return name.TrimEnd('.', '-')+".aspx";
        }


        public override sealed SPQuery Query { get; protected set; }
        private SPQuery DefautQuery()
        {
            return new SPQuery
            {
                ViewAttributes = "Scope='Recursive'",
                RowLimit = 100,
                Query = "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\"/></OrderBy>"
            };
        }
    }
}